import { useStorage } from 'ew-responsive-store';
import { isObject, isString } from 'lodash-es';

// 语言类型定义
export type Language = 'zh-CN' | 'en-US';

// 语言配置
export const languages = {
    'zh-CN': {
        name: '中文',
        flag: '🇨🇳'
    },
    'en-US': {
        name: 'English',
        flag: '🇺🇸'
    }
};

// 翻译内容
export const translations = {
    'zh-CN': {
        // 通用
        common: {
            loading: '加载中...',
            error: '错误',
            success: '成功',
            cancel: '取消',
            confirm: '确认',
            back: '返回',
            next: '下一步',
            previous: '上一步',
            close: '关闭',
            decimal: '十进制的'
        },
        // 导航
        nav: {
            home: '首页',
            about: '关于',
            levels: '关卡',
            progress: '进度'
        },
        // 首页
        home: {
            title: '欢迎来到',
            subtitle: '通过互动游戏掌握 JavaScript 位运算',
            startLearning: '开始学习',
            resetProgress: '重置进度',
            progressText: '完成进度',
            levelsTitle: '学习关卡',
            resetConfirmTitle: '确认重置',
            resetConfirmMessage: '你确定要重置所有学习进度吗？此操作不可撤销。',
            cancel: '取消',
            confirm: '确认重置',
            appName: '位运算大师'
        },
        // 关于页面
        about: {
            title: '关于位运算',
            whatIsBitwise: '什么是位运算？',
            whatIsBitwiseDesc1: '位运算是直接对二进制位进行操作的运算。在JavaScript中，位运算可以用于处理整数的二进制表示，执行效率高，在特定场景下能够大幅提升性能。',
            whatIsBitwiseDesc2: '所有的数字在计算机内部都是以二进制形式存储的，位运算直接操作这些二进制位，因此在某些场景下比普通的算术运算更高效。',
            operatorsTitle: 'JavaScript中的位运算符',
            andOperator: '按位与（AND）',
            andDesc: '对两个操作数的每一位执行与操作。只有两个位都为1时，结果才为1，否则为0。',
            orOperator: '按位或（OR）',
            orDesc: '对两个操作数的每一位执行或操作。只要有一个位为1，结果就为1，否则为0。',
            xorOperator: '按位异或（XOR）',
            xorDesc: '对两个操作数的每一位执行异或操作。两个位不同时，结果为1，相同时为0。',
            notOperator: '按位非（NOT）',
            notDesc: '对操作数的每一位执行非操作，即将0变为1，将1变为0。',
            leftShift: '左移',
            leftShiftDesc: '将操作数的所有位向左移动指定的位数，右侧补0。',
            rightShift: '右移',
            rightShiftDesc: '将操作数的所有位向右移动指定的位数，左侧补符号位（正数补0，负数补1）。',
            unsignedRightShift: '无符号右移',
            unsignedRightShiftDesc: '将操作数的所有位向右移动指定的位数，左侧始终补0。',
            applicationsTitle: '位运算的应用场景',
            permissionControl: '权限控制：使用位掩码表示不同的权限，通过位运算快速检查和修改权限。',
            graphicsProcessing: '图形处理：在图像处理中，位运算可用于颜色混合、像素操作等。',
            performanceOptimization: '性能优化：在某些场景下，使用位运算替代乘除法可以提高性能。例如，x << 1 等价于 x * 2。',
            dataCompression: '数据压缩：利用位运算可以在有限的空间内存储更多信息。',
            encryption: '加密算法：许多加密算法使用位运算作为基本操作。',
            gameDevelopment: '游戏开发：在游戏开发中，位运算常用于碰撞检测、状态管理等。',
            aboutAppTitle: '关于本应用',
            aboutAppDesc1: '「位运算大师」是一个互动式学习平台，旨在帮助前端开发者和JavaScript学习者掌握位运算的概念和应用。通过一系列精心设计的关卡，你将逐步学习各种位运算符的用法和实际应用场景。',
            aboutAppDesc2: '每个关卡都包含理论知识讲解、编程挑战和即时反馈，帮助你巩固所学知识。完成所有关卡后，你将能够自信地在实际项目中应用位运算技巧。',
            backToHome: '返回主页'
        },
        // 关卡相关
        level: {
            level: '关卡',
            completed: '已完成',
            notCompleted: '未完成',
            theory: '知识点',
            challenge: '挑战',
            runCode: '运行代码',
            resetCode: '重置代码',
            runResult: '运行结果',
            congratulations: '恭喜！你的代码通过了所有测试用例！',
            greatJob: '🎉 太棒了！你已经掌握了这个概念！',
            testFailed: '测试未通过',
            codeError: '代码执行错误',
            needHelp: '需要帮助？',
            viewHint: '查看提示',
            hideHint: '隐藏提示',
            viewSolution: '查看解答',
            hideSolution: '隐藏解答',
            referenceSolution: '参考解答',
            solutionNote: '记住，理解概念比记忆代码更重要！',
            hint: '提示',
            previousLevel: '上一关',
            nextLevel: '下一关',
            completeCurrentToContinue: '完成当前关卡以继续',
            returnHome: '返回首页',
            input: '输入',
            expected: '期望',
            actual: '实际',
            implementCodeHere: '// 在这里实现代码'
        },
        // 关卡数据
        levels: {
            level1: {
                name: '位运算基础',
                theoryTitle: '二进制基础',
                theoryDesc1: '在计算机中，所有数据都以二进制形式存储。二进制只有0和1两个数字，分别代表关(off)和开(on)。',
                theoryDesc2: '十进制数字转换为二进制的方法是不断除以2，记录余数，然后从下往上读取余数。例如：',
                theoryExample: '十进制10转二进制：\n10 ÷ 2 = 5 余 0\n5 ÷ 2 = 2 余 1\n2 ÷ 2 = 1 余 0\n1 ÷ 2 = 0 余 1\n从下往上读：1010',
                theoryDesc3: '在JavaScript中，整数以32位二进制形式存储，最高位是符号位（0表示正数，1表示负数）。',
                theoryDesc4: '可以使用toString(2)方法将十进制数转换为二进制字符串：',
                theoryCode1: 'const num = 10;\nconsole.log(num.toString(2)); // 输出: "1010"',
                theoryDesc5: '也可以使用parseInt(str, 2)将二进制字符串转换为十进制数：',
                theoryCode2: 'const binary = "1010";\nconsole.log(parseInt(binary, 2)); // 输出: 10',
                challenge: '编写一个函数，接收一个十进制整数作为参数，返回它的二进制表示形式（字符串）。不要使用内置的toString方法。',
                hint: '可以使用除以2取余数的方法，将余数存入数组，最后反转数组并连接成字符串。'
            },
            level2: {
                name: '按位与（AND）',
                theoryTitle: '按位与运算符 (&)',
                theoryDesc1: '按位与运算符对两个操作数的每一位执行与操作。只有当两个相应的位都为1时，结果才为1，否则为0。',
                theoryDesc2: '按位与可以用来检查一个数的特定位是否为1，或者将某些位清零。',
                theoryExample: '示例：5 & 3\n5 的二进制：101\n3 的二进制：011\n结果：       001 (十进制为1)',
                theoryDesc3: '常见用途：',
                theoryUse1: '检查一个数是奇数还是偶数：num & 1如果结果为1，则为奇数；如果为0，则为偶数。',
                theoryUse2: '清除特定位：将想要保留的位设为1，其他位设为0，然后与原数进行按位与操作。',
                theoryUse3: '判断两个数的符号是否相同：(a ^ b) >= 0',
                challenge: '编写一个函数，判断一个数是否是2的幂（即2的n次方）。提示：2的幂在二进制中只有一个1。',
                hint: '如果一个数是2的幂，那么它的二进制表示中只有一个1。可以利用 n & (n-1) 来判断。'
            },
            level3: {
                name: '按位或（OR）',
                theoryTitle: '按位或运算符 (|)',
                theoryDesc1: '按位或运算符对两个操作数的每一位执行或操作。如果两个相应的位中至少有一个为1，则结果为1，否则为0。',
                theoryDesc2: '按位或可以用来将某些位设置为1，同时保留其他位不变。',
                theoryExample: '示例：5 | 3\n5 的二进制：101\n3 的二进制：011\n结果：       111 (十进制为7)',
                theoryDesc3: '常见用途：',
                theoryUse1: '设置特定位：将想要设置的位设为1，其他位设为0，然后与原数进行按位或操作。',
                theoryUse2: '合并标志位：在使用位掩码表示多个布尔值时，可以使用按位或来添加标志。',
                challenge: '编写一个函数，接收两个整数作为参数，返回将第一个整数的第n位（从右往左，从0开始计数）设置为1后的结果。',
                hint: '可以使用按位或运算符和左移运算符。创建一个只有第n位为1的掩码，然后与原数进行按位或操作。'
            },
            level4: {
                name: '按位异或（XOR）',
                theoryTitle: '按位异或运算符 (^)',
                theoryDesc1: '按位异或运算符对两个操作数的每一位执行异或操作。如果两个相应的位不同，则结果为1，如果相同则为0。',
                theoryDesc2: '按位异或有一些有趣的性质，例如：',
                theoryExample: '示例：5 ^ 3\n5 的二进制：101\n3 的二进制：011\n结果：       110 (十进制为6)',
                theoryDesc3: '常见用途：',
                theoryUse1: '切换位的值：对一个数的特定位进行异或操作，可以切换该位的值（0变1，1变0）。',
                theoryUse2: '不使用临时变量交换两个变量的值：a = a ^ b; b = a ^ b; a = a ^ b;',
                theoryUse3: '查找数组中只出现一次的数：如果一个数组中除了一个数字只出现一次外，其他数字都出现两次，那么对所有数字进行异或操作，结果就是那个只出现一次的数字。',
                challenge: '编写一个函数，接收一个整数数组，其中除了一个数字只出现一次外，其他数字都出现了两次。找出并返回那个只出现一次的数字。',
                hint: '利用异或运算的性质：a ^ a = 0 和 a ^ 0 = a。对数组中所有元素进行异或操作，最终结果就是只出现一次的数字。'
            },
            level5: {
                name: '按位非（NOT）',
                theoryTitle: '按位非运算符 (~)',
                theoryDesc1: '按位非运算符对操作数的每一位执行非操作，即将0变为1，将1变为0。这相当于对数字取反再减1。',
                theoryDesc2: '在JavaScript中，数字以32位二进制形式存储，按位非运算会影响所有这32位。',
                theoryExample: '示例：~5\n5 的二进制（32位）：00000000000000000000000000000101\n~5 的结果：          11111111111111111111111111111010 (十进制为-6)',
                theoryDesc3: '为什么~5等于-6？这是因为JavaScript使用二进制补码表示负数。对一个数取反再加1，就得到它的相反数。所以~n = -(n+1)。',
                theoryDesc4: '常见用途：',
                theoryUse1: '快速取整：~~3.14等于3（相当于Math.floor对正数的效果）',
                theoryUse2: '检查数组中是否存在某个元素：if(~arr.indexOf(item))比if(arr.indexOf(item) !== -1)更简洁',
                challenge: '编写一个函数，接收一个整数作为参数，返回将该整数所有位取反后的结果。',
                hint: '直接使用按位非运算符~，但要注意JavaScript中的数字表示方式。'
            },
            level6: {
                name: '左移（<<）',
                theoryTitle: '左移运算符 (<<)',
                theoryDesc1: '左移运算符将操作数的所有位向左移动指定的位数，右侧补0。这相当于将数字乘以2的n次方。',
                theoryExample: '示例：5 << 1\n5 的二进制：101\n左移1位后：  1010 (十进制为10)\n\n示例：5 << 2\n5 的二进制：101\n左移2位后：  10100 (十进制为20)',
                theoryDesc2: '左移n位相当于乘以2的n次方：x << n等价于x * Math.pow(2, n)，但位运算通常更高效。',
                theoryDesc3: '常见用途：',
                theoryUse1: '快速乘法：当需要将一个数乘以2的幂时，使用左移运算更高效。',
                theoryUse2: '创建掩码：生成特定位模式的掩码。',
                challenge: '编写一个函数，计算2的n次方（n为非负整数）。使用左移运算符实现，不要使用Math.pow()。',
                hint: '可以使用左移运算符，1 << n 相当于 2^n。'
            },
            level7: {
                name: '右移（>>）',
                theoryTitle: '右移运算符 (>>)',
                theoryDesc1: '右移运算符将操作数的所有位向右移动指定的位数，丢弃移除的位。对于正数，左侧补0；对于负数，左侧补1（保持符号位）。',
                theoryDesc2: '这相当于将数字除以2的n次方并向下取整。',
                theoryExample: '示例：10 >> 1\n10 的二进制：1010\n右移1位后：  0101 (十进制为5)\n\n示例：-10 >> 1\n-10 的二进制（简化表示）：...1111111111110110\n右移1位后：              ...1111111111111011 (十进制为-5)',
                theoryDesc3: '右移n位相当于除以2的n次方并向下取整：x >> n近似等价于Math.floor(x / Math.pow(2, n))。',
                theoryDesc4: '常见用途：',
                theoryUse1: '快速除法：当需要将一个数除以2的幂时，使用右移运算更高效。',
                theoryUse2: '保持符号的整数除法。',
                challenge: '编写一个函数，接收一个整数作为参数，返回将该整数除以2并向下取整的结果。使用右移运算符实现。',
                hint: '使用右移1位运算符 >> 可以实现除以2并向下取整的效果。'
            },
            level8: {
                name: '无符号右移（>>>）',
                theoryTitle: '无符号右移运算符 (>>>)',
                theoryDesc1: '无符号右移运算符将操作数的所有位向右移动指定的位数，丢弃移除的位，左侧始终补0，不考虑符号位。',
                theoryDesc2: '这与有符号右移(>>)的区别在于，无论操作数是正数还是负数，左侧都补0。',
                theoryExample: '示例：10 >>> 1\n10 的二进制：00000000000000000000000000001010\n右移1位后：  00000000000000000000000000000101 (十进制为5)\n\n示例：-10 >>> 1\n-10 的二进制：11111111111111111111111111110110\n右移1位后：   01111111111111111111111111111011 (十进制为2147483643)',
                theoryDesc3: '对于正数，>>> 和 >> 的结果相同。但对于负数，结果会非常不同，因为符号位也参与了移位。',
                theoryDesc4: '常见用途：',
                theoryUse1: '处理无符号整数：在需要将负数视为大的无符号数时使用。',
                theoryUse2: '实现无符号除法。',
                challenge: '编写一个函数，接收一个整数作为参数，返回将该整数的所有位向右移动1位，左侧补0的结果。',
                hint: '使用无符号右移运算符 >>> 可以实现向右移动并左侧补0的效果。'
            },
            level9: {
                name: '位掩码应用',
                theoryTitle: '位掩码',
                theoryDesc1: '位掩码是使用二进制位来存储多个布尔值（标志）的技术。每一位代表一个标志，可以通过位运算来设置、清除、切换或检查这些标志。',
                theoryDesc2: '位掩码在需要存储多个开关状态但又想节省内存时非常有用。例如，在权限系统、图形处理和游戏开发中经常使用。',
                theoryDesc3: '常用的位掩码操作：',
                theoryUse1: '设置标志：flags |= mask',
                theoryUse2: '清除标志：flags &= ~mask',
                theoryUse3: '切换标志：flags ^= mask',
                theoryUse4: '检查标志：(flags & mask) !== 0',
                theoryExample: '例如，我们可以用一个整数的不同位来表示用户的权限：\n\nconst READ = 1;          // 0001\nconst WRITE = 2;         // 0010\nconst EXECUTE = 4;       // 0100\nconst ADMIN = 8;         // 1000\n\n// 授予用户读和写权限\nlet userPermissions = READ | WRITE;  // 0011 (3)\n\n// 检查用户是否有读权限\nif (userPermissions & READ) {\n  console.log("用户有读权限");\n}\n\n// 添加执行权限\nuserPermissions |= EXECUTE;  // 0111 (7)\n\n// 移除写权限\nuserPermissions &= ~WRITE;   // 0101 (5)',
                challenge: '实现一个简单的权限系统。编写一个函数，接收用户当前权限和要检查的权限作为参数，返回用户是否拥有该权限。',
                hint: '使用按位与运算符检查特定权限位是否设置。如果 (userPermissions & permissionToCheck) !== 0，则用户拥有该权限。'
            },
            level10: {
                name: '位运算技巧',
                theoryTitle: '位运算技巧',
                theoryDesc1: '位运算可以用来实现许多常见操作，通常比传统方法更高效。以下是一些常用的位运算技巧：',
                theoryDesc2: '常用技巧：',
                theoryUse1: '判断奇偶性：n & 1 === 0（偶数），n & 1 === 1（奇数）',
                theoryUse2: '交换两个变量的值（不使用临时变量）：a ^= b; b ^= a; a ^= b;',
                theoryUse3: '取绝对值（仅适用于32位整数）：const abs = (n ^ (n >> 31)) - (n >> 31);',
                theoryUse4: '取整（向下取整，仅适用于正数）：const floor = n >> 0;',
                theoryUse5: '计算2的幂：const pow2 = 1 << n（计算2的n次方）',
                theoryUse6: '乘以/除以2的幂：n << m（n乘以2的m次方），n >> m（n除以2的m次方，向下取整）',
                theoryUse7: '检查一个数是否是2的幂：n & (n - 1) === 0 && n > 0',
                theoryUse8: '计算平均值（避免溢出）：const avg = (a & b) + ((a ^ b) >> 1);',
                challenge: '编写一个函数，接收两个整数作为参数，返回它们的平均值（向下取整）。使用位运算实现，避免可能的溢出问题。',
                hint: '可以使用 (a & b) + ((a ^ b) >> 1) 计算平均值，这种方法可以避免 (a + b) / 2 可能导致的溢出问题。'
            }
        }
    },
    'en-US': {
        // Common
        common: {
            loading: 'Loading...',
            error: 'Error',
            success: 'Success',
            cancel: 'Cancel',
            confirm: 'Confirm',
            back: 'Back',
            next: 'Next',
            previous: 'Previous',
            close: 'Close',
            decimal: 'Decimal'
        },
        // Navigation
        nav: {
            home: 'Home',
            about: 'About',
            levels: 'Levels',
            progress: 'Progress'
        },
        // Home page
        home: {
            title: 'Welcome to',
            subtitle: 'Master JavaScript Bitwise Operations through Interactive Games',
            startLearning: 'Start Learning',
            resetProgress: 'Reset Progress',
            progressText: 'Completion Progress',
            levelsTitle: 'Learning Levels',
            resetConfirmTitle: 'Confirm Reset',
            resetConfirmMessage: 'Are you sure you want to reset all learning progress? This action cannot be undone.',
            cancel: 'Cancel',
            confirm: 'Confirm Reset',
            appName: 'Bitwise Master'
        },
        // About page
        about: {
            title: 'About Bitwise Operations',
            whatIsBitwise: 'What are Bitwise Operations?',
            whatIsBitwiseDesc1: 'Bitwise operations are operations that directly manipulate binary bits. In JavaScript, bitwise operations can be used to process binary representations of integers, with high execution efficiency and significant performance improvements in specific scenarios.',
            whatIsBitwiseDesc2: 'All numbers are stored in binary form inside computers, and bitwise operations directly manipulate these binary bits, making them more efficient than regular arithmetic operations in certain scenarios.',
            operatorsTitle: 'Bitwise Operators in JavaScript',
            andOperator: 'Bitwise AND',
            andDesc: 'Performs AND operation on each bit of two operands. Result is 1 only when both bits are 1, otherwise 0.',
            orOperator: 'Bitwise OR',
            orDesc: 'Performs OR operation on each bit of two operands. Result is 1 when at least one bit is 1, otherwise 0.',
            xorOperator: 'Bitwise XOR',
            xorDesc: 'Performs XOR operation on each bit of two operands. Result is 1 when bits are different, 0 when they are the same.',
            notOperator: 'Bitwise NOT',
            notDesc: 'Performs NOT operation on each bit of the operand, turning 0 to 1 and 1 to 0.',
            leftShift: 'Left Shift',
            leftShiftDesc: 'Shifts all bits of the operand to the left by the specified number of positions, filling the right side with 0s.',
            rightShift: 'Right Shift',
            rightShiftDesc: 'Shifts all bits of the operand to the right by the specified number of positions, filling the left side with the sign bit (0 for positive numbers, 1 for negative numbers).',
            unsignedRightShift: 'Unsigned Right Shift',
            unsignedRightShiftDesc: 'Shifts all bits of the operand to the right by the specified number of positions, always filling the left side with 0s.',
            applicationsTitle: 'Applications of Bitwise Operations',
            permissionControl: 'Permission Control: Use bitmasks to represent different permissions, quickly check and modify permissions through bitwise operations.',
            graphicsProcessing: 'Graphics Processing: In image processing, bitwise operations can be used for color blending, pixel manipulation, etc.',
            performanceOptimization: 'Performance Optimization: In certain scenarios, using bitwise operations instead of multiplication/division can improve performance. For example, x << 1 is equivalent to x * 2.',
            dataCompression: 'Data Compression: Utilize bitwise operations to store more information in limited space.',
            encryption: 'Encryption Algorithms: Many encryption algorithms use bitwise operations as basic operations.',
            gameDevelopment: 'Game Development: In game development, bitwise operations are commonly used for collision detection, state management, etc.',
            aboutAppTitle: 'About This App',
            aboutAppDesc1: '"Bitwise Master" is an interactive learning platform designed to help frontend developers and JavaScript learners master the concepts and applications of bitwise operations. Through a series of carefully designed levels, you will gradually learn the usage and practical application scenarios of various bitwise operators.',
            aboutAppDesc2: 'Each level includes theoretical knowledge explanation, programming challenges, and immediate feedback to help you consolidate what you have learned. After completing all levels, you will be able to confidently apply bitwise operation techniques in real projects.',
            backToHome: 'Back to Home'
        },
        // Level related
        level: {
            level: 'Level',
            completed: 'Completed',
            notCompleted: 'Not Completed',
            theory: 'Theory',
            challenge: 'Challenge',
            runCode: 'Run Code',
            resetCode: 'Reset Code',
            runResult: 'Run Result',
            congratulations: 'Congratulations! Your code passed all test cases!',
            greatJob: '🎉 Great job! You have mastered this concept!',
            testFailed: 'Test failed',
            codeError: 'Code execution error',
            needHelp: 'Need help?',
            viewHint: 'View Hint',
            hideHint: 'Hide Hint',
            viewSolution: 'View Solution',
            hideSolution: 'Hide Solution',
            referenceSolution: 'Reference Solution',
            solutionNote: 'Remember, understanding concepts is more important than memorizing code!',
            hint: 'Hint',
            previousLevel: 'Previous Level',
            nextLevel: 'Next Level',
            completeCurrentToContinue: 'Complete current level to continue',
            returnHome: 'Return to Home',
            input: 'Input',
            expected: 'Expected',
            actual: 'Actual',
            implementCodeHere: '// Implement your code here'
        },
        // 关卡数据
        levels: {
            level1: {
                name: 'Bitwise Basics',
                theoryTitle: 'Binary Basics',
                theoryDesc1: 'In computers, all data is stored in binary form. Binary consists of only 0 and 1, representing off and on, respectively.',
                theoryDesc2: 'The method to convert decimal numbers to binary is to divide by 2 repeatedly, record the remainder, and then read from bottom to top. For example:',
                theoryExample: 'Decimal 10 to Binary:\n10 ÷ 2 = 5 remainder 0\n5 ÷ 2 = 2 remainder 1\n2 ÷ 2 = 1 remainder 0\n1 ÷ 2 = 0 remainder 1\nRead from bottom to top: 1010',
                theoryDesc3: 'In JavaScript, integers are stored in 32-bit binary form, with the highest bit being the sign bit (0 for positive, 1 for negative).',
                theoryDesc4: 'You can use the toString(2) method to convert a decimal number to a binary string:',
                theoryCode1: 'const num = 10;\nconsole.log(num.toString(2)); // Output: "1010"',
                theoryDesc5: 'You can also use parseInt(str, 2) to convert a binary string to a decimal number:',
                theoryCode2: 'const binary = "1010";\nconsole.log(parseInt(binary, 2)); // Output: 10',
                challenge: 'Write a function that takes a decimal integer as an argument and returns its binary representation (string). Do not use the built-in toString method.',
                hint: 'You can use the method of dividing by 2 to get the remainder, store the remainder in an array, and then reverse the array and concatenate it into a string.'
            },
            level2: {
                name: 'Bitwise AND (&)',
                theoryTitle: 'Bitwise AND Operator (&)',
                theoryDesc1: 'The Bitwise AND operator performs AND operation on each bit of two operands. The result is 1 only when both corresponding bits are 1, otherwise 0.',
                theoryDesc2: 'Bitwise AND can be used to check if a specific bit of a number is 1, or to clear certain bits.',
                theoryExample: 'Example: 5 & 3\nBinary of 5: 101\nBinary of 3: 011\nResult:       001 (Decimal: 1)',
                theoryDesc3: 'Common uses:',
                theoryUse1: 'Check if a number is odd or even: num & 1. If the result is 1, it is odd; if 0, it is even.',
                theoryUse2: 'Clear specific bits: Set the bits you want to keep to 1, and 0 to others, then perform a bitwise AND operation with the original number.',
                theoryUse3: 'Check if the signs of two numbers are the same: (a ^ b) >= 0',
                challenge: 'Write a function to determine if a number is a power of 2 (i.e., 2^n). Hint: A power of 2 in binary has only one 1.',
                hint: 'If a number is a power of 2, its binary representation has only one 1. You can use n & (n-1) to determine.'
            },
            level3: {
                name: 'Bitwise OR (|)',
                theoryTitle: 'Bitwise OR Operator (|)',
                theoryDesc1: 'The Bitwise OR operator performs OR operation on each bit of two operands. The result is 1 when at least one bit is 1, otherwise 0.',
                theoryDesc2: 'Bitwise OR can be used to set certain bits to 1 while keeping other bits unchanged.',
                theoryExample: 'Example: 5 | 3\nBinary of 5: 101\nBinary of 3: 011\nResult:       111 (Decimal: 7)',
                theoryDesc3: 'Common uses:',
                theoryUse1: 'Set specific bits: Set the bits you want to set to 1, and 0 to others, then perform a bitwise OR operation with the original number.',
                theoryUse2: 'Combine flag bits: When using bitmasks to represent multiple boolean values, you can use bitwise OR to add flags.',
                challenge: 'Write a function that takes two integers as arguments and returns the result after setting the nth bit (from right to left, starting from 0) of the first integer to 1.',
                hint: 'You can use the bitwise OR operator and the left shift operator. Create a mask with only the nth bit set to 1, then perform a bitwise OR operation with the original number.'
            },
            level4: {
                name: 'Bitwise XOR (^)',
                theoryTitle: 'Bitwise XOR Operator (^)',
                theoryDesc1: 'The Bitwise XOR operator performs XOR operation on each bit of two operands. The result is 1 when the corresponding bits are different, otherwise 0.',
                theoryDesc2: 'Bitwise XOR has some interesting properties, such as:',
                theoryExample: 'Example: 5 ^ 3\nBinary of 5: 101\nBinary of 3: 011\nResult:       110 (Decimal: 6)',
                theoryDesc3: 'Common uses:',
                theoryUse1: 'Toggle bit values: Performing XOR operation on a specific bit of a number can toggle the value of that bit (0 to 1, 1 to 0).',
                theoryUse2: 'Swap values of two variables (without using a temporary variable): a = a ^ b; b = a ^ b; a = a ^ b;',
                theoryUse3: 'Find the number that appears only once in an array: If an array contains only one number that appears only once, and all other numbers appear twice, then performing XOR operation on all numbers results in that number that appears only once.',
                challenge: 'Write a function that takes an integer array, in which all numbers except one appear twice. Find and return the number that appears only once.',
                hint: 'Utilize the properties of XOR operation: a ^ a = 0 and a ^ 0 = a. Performing XOR operation on all elements of the array results in the number that appears only once.'
            },
            level5: {
                name: 'Bitwise NOT (~)',
                theoryTitle: 'Bitwise NOT Operator (~)',
                theoryDesc1: 'The Bitwise NOT operator performs NOT operation on each bit of the operand, turning 0 to 1 and 1 to 0. This is equivalent to taking the number and subtracting 1, then taking the bitwise NOT.',
                theoryDesc2: 'In JavaScript, numbers are stored in 32-bit binary form, and the bitwise NOT operation affects all 32 bits.',
                theoryExample: 'Example: ~5\nBinary of 5 (32-bit): 00000000000000000000000000000101\n~5 result:          11111111111111111111111111111010 (Decimal: -6)',
                theoryDesc3: 'Why is ~5 equal to -6? This is because JavaScript uses two\'s complement to represent negative numbers. Taking the bitwise NOT of a number and adding 1 gives its opposite. So ~n = -(n+1).',
                theoryDesc4: 'Common uses:',
                theoryUse1: 'Quick rounding: ~~3.14 equals 3 (equivalent to Math.floor for positive numbers)',
                theoryUse2: 'Check if an element exists in an array: if(~arr.indexOf(item)) is more concise than if(arr.indexOf(item) !== -1)',
                challenge: 'Write a function that takes an integer as an argument and returns the result after inverting all its bits.',
                hint: 'Directly use the bitwise NOT operator ~, but be aware of the number representation in JavaScript.'
            },
            level6: {
                name: 'Left Shift (<<)',
                theoryTitle: 'Left Shift Operator (<<)',
                theoryDesc1: 'The Left Shift operator shifts all bits of the operand to the left by the specified number of positions, filling the right side with 0s. This is equivalent to multiplying the number by 2 to the nth power.',
                theoryExample: 'Example: 5 << 1\nBinary of 5: 101\nAfter left shift by 1:  1010 (Decimal: 10)\n\nExample: 5 << 2\nBinary of 5: 101\nAfter left shift by 2:  10100 (Decimal: 20)',
                theoryDesc2: 'Left shift n bits is equivalent to multiplying by 2 to the nth power: x << n is equivalent to x * Math.pow(2, n), but bitwise operations are usually more efficient.',
                theoryDesc3: 'Common uses:',
                theoryUse1: 'Quick multiplication: When you need to multiply a number by a power of 2, using left shift is more efficient.',
                theoryUse2: 'Create masks: Generate masks for specific bit patterns.',
                challenge: 'Write a function that calculates 2 to the nth power (n is a non-negative integer). Implement using left shift, do not use Math.pow().',
                hint: 'You can use the left shift operator, 1 << n is equivalent to 2^n.'
            },
            level7: {
                name: 'Right Shift (>>)',
                theoryTitle: 'Right Shift Operator (>>)',
                theoryDesc1: 'The Right Shift operator shifts all bits of the operand to the right by the specified number of positions, discarding the removed bits. For positive numbers, it fills the left side with 0; for negative numbers, it fills the left side with 1 (to keep the sign bit).',
                theoryDesc2: 'This is equivalent to dividing the number by 2 to the nth power and rounding down.',
                theoryExample: 'Example: 10 >> 1\nBinary of 10: 1010\nAfter right shift by 1:  0101 (Decimal: 5)\n\nExample: -10 >> 1\nBinary of -10 (simplified): ...1111111111110110\nAfter right shift by 1:              ...1111111111111011 (Decimal: -5)',
                theoryDesc3: 'Right shift n bits is equivalent to dividing by 2 to the nth power and rounding down: x >> n is approximately equivalent to Math.floor(x / Math.pow(2, n)).',
                theoryDesc4: 'Common uses:',
                theoryUse1: 'Quick division: When you need to divide a number by a power of 2, using right shift is more efficient.',
                theoryUse2: 'Integer division with sign preservation.',
                challenge: 'Write a function that takes an integer as an argument and returns the result of dividing the integer by 2 and rounding down. Implement using right shift operator.',
                hint: 'Using the right shift operator >> 1 can achieve the effect of dividing by 2 and rounding down.'
            },
            level8: {
                name: 'Unsigned Right Shift (>>>)',
                theoryTitle: 'Unsigned Right Shift Operator (>>>)',
                theoryDesc1: 'The Unsigned Right Shift operator shifts all bits of the operand to the right by the specified number of positions, discarding the removed bits, and always fills the left side with 0s, without considering the sign bit.',
                theoryDesc2: 'This is different from signed right shift (>>), where regardless of whether the operand is positive or negative, the left side is always filled with 0s.',
                theoryExample: 'Example: 10 >>> 1\nBinary of 10: 00000000000000000000000000001010\nAfter right shift by 1:  00000000000000000000000000000101 (Decimal: 5)\n\nExample: -10 >>> 1\nBinary of -10: 11111111111111111111111111110110\nAfter right shift by 1:   01111111111111111111111111111011 (Decimal: 2147483643)',
                theoryDesc3: 'For positive numbers, the results of >>> and >> are the same. However, for negative numbers, the results will be very different because the sign bit is also involved in the shift.',
                theoryDesc4: 'Common uses:',
                theoryUse1: 'Handle unsigned integers: Use when you need to treat negative numbers as large unsigned numbers.',
                theoryUse2: 'Implement unsigned division.',
                challenge: 'Write a function that takes an integer as an argument and returns the result of shifting the integer to the right by 1 bit and padding with 0 on the left.',
                hint: 'Using the unsigned right shift operator >>> can achieve the effect of shifting to the right and padding with 0 on the left.'
            },
            level9: {
                name: 'Bitmask Applications',
                theoryTitle: 'Bitmask',
                theoryDesc1: 'Bitmasking is a technique that uses binary bits to store multiple boolean values (flags). Each bit represents a flag, which can be set, cleared, toggled, or checked using bitwise operations.',
                theoryDesc2: 'Bitmasks are very useful when you need to store multiple switch states but want to save memory. For example, they are often used in permission systems, graphics processing, and game development.',
                theoryDesc3: 'Common bitmask operations:',
                theoryUse1: 'Set flag: flags |= mask',
                theoryUse2: 'Clear flag: flags &= ~mask',
                theoryUse3: 'Toggle flag: flags ^= mask',
                theoryUse4: 'Check flag: (flags & mask) !== 0',
                theoryExample: 'For example, we can use different bits of an integer to represent user permissions:\n\nconst READ = 1;          // 0001\nconst WRITE = 2;         // 0010\nconst EXECUTE = 4;       // 0100\nconst ADMIN = 8;         // 1000\n\n// Grant user read and write permissions\nlet userPermissions = READ | WRITE;  // 0011 (3)\n\n// Check if user has read permission\nif (userPermissions & READ) {\n  console.log("User has read permission");\n}\n\n// Add execute permission\nuserPermissions |= EXECUTE;  // 0111 (7)\n\n// Remove write permission\nuserPermissions &= ~WRITE;   // 0101 (5)',
                challenge: 'Implement a simple permission system. Write a function that takes the user\'s current permissions and the permission to check as arguments, and returns whether the user has that permission.',
                hint: 'Check if a specific permission bit is set using the bitwise AND operator. If (userPermissions & permissionToCheck) !== 0, the user has that permission.'
            },
            level10: {
                name: 'Bitwise Tricks',
                theoryTitle: 'Bitwise Tricks',
                theoryDesc1: 'Bitwise operations can be used to implement many common operations, often more efficiently than traditional methods. Here are some common bitwise tricks:',
                theoryDesc2: 'Common tricks:',
                theoryUse1: 'Check for odd/even: n & 1 === 0 (even), n & 1 === 1 (odd)',
                theoryUse2: 'Swap values of two variables (without using a temporary variable): a ^= b; b ^= a; a ^= b;',
                theoryUse3: 'Get absolute value (only for 32-bit integers): const abs = (n ^ (n >> 31)) - (n >> 31);',
                theoryUse4: 'Get integer (floor, only for positive numbers): const floor = n >> 0;',
                theoryUse5: 'Calculate power of 2: const pow2 = 1 << n (calculate 2 to the nth power)',
                theoryUse6: 'Multiply/divide by power of 2: n << m (n times 2 to the mth power), n >> m (n divided by 2 to the mth power, rounded down)',
                theoryUse7: 'Check if a number is a power of 2: n & (n - 1) === 0 && n > 0',
                theoryUse8: 'Calculate average (avoid overflow): const avg = (a & b) + ((a ^ b) >> 1);',
                challenge: 'Write a function that takes two integers as arguments and returns their average (rounded down). Implement using bitwise operations, avoiding potential overflow issues.',
                hint: 'You can calculate the average using (a & b) + ((a ^ b) >> 1), this method can avoid potential overflow issues that might occur with (a + b) / 2.'
            }
        }
    }
};

export type Translations = typeof translations;
export type TranslationKey = keyof Translations;

// 本地存储键名
const LANGUAGE_STORAGE_KEY = "js-bitwise-operations-language";

// 默认语言
const defaultLanguage: Language = (() => {
    // 默认使用浏览器语言或中文
    const browserLang = navigator.language;
    if (browserLang.startsWith('zh')) {
        return 'zh-CN';
    }
    return 'en-US';
})();

// 响应式语言状态
const currentLanguage = useStorage<Language>(LANGUAGE_STORAGE_KEY, defaultLanguage);

// 获取当前语言
export function getCurrentLanguage(): Language {
    return currentLanguage.value;
}

// 设置语言
export function setLanguage(lang: Language) {
    currentLanguage.value = lang;
}

// 获取翻译文本
export function t(key: string, lang: Language = getCurrentLanguage()): string {
    const keys = key.split('.');
    let value: any = translations[lang];
    
    for (const k of keys) {
        if (isObject(value) && k in value) {
            value = value[k as keyof typeof value];
        } else {
            return key;
        }
    }
    
    return isString(value) ? value : key;
}

// 创建响应式的语言状态
export function useLanguage() {
    return {
        currentLang: currentLanguage,
        setLanguage: (lang: Language) => {
            setLanguage(lang);
        },
        t: (key: string) => t(key, currentLanguage.value)
    };
}
